package com.huayi.server.NioServer;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ServerIntializer extends ChannelInitializer<SocketChannel> {

    Logger logger = LoggerFactory.getLogger(ServerIntializer.class);

    @Autowired
    DeviceManager deviceManager;

    @Autowired
    ServerHandler serverHandler;

    protected void initChannel(SocketChannel socketChannel) throws Exception {

        serverHandler.setDeviceManager(deviceManager);
        ChannelPipeline pipeline = socketChannel.pipeline();
        pipeline.addLast(new LoggingHandler(LogLevel.ERROR));
        pipeline.addLast(new DelimiterBasedFrameDecoder(1024, Unpooled.copiedBuffer(new byte[]{(byte) 0xc0}),Unpooled.copiedBuffer(new byte[]{(byte) 0xc0, (byte) 0xc0})));
        pipeline.addLast(new MessageDecode());
        pipeline.addLast(new MessageEncode());
        pipeline.addLast(serverHandler);
    }
}
